package com.hundred.user.manager.impl;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.hundred.home.module.screen.Index;
import com.hundred.user.dao.UserDAO;
import com.hundred.user.dao.dataobject.AppUserDO;
import com.hundred.user.manager.UserManager;
import com.qq.open.ErrorCode;
import com.qq.open.OpenApiV3;
import com.qq.open.OpensnsException;

public class UserManagerImpl implements UserManager{

	private static final Logger logger = LoggerFactory.getLogger(UserManagerImpl.class);
	@Autowired
	private UserDAO userDAO;
	
	public AppUserDO getAppUserByUserId(String userId) {
		
		return userDAO.getAppUserByUserId(userId);
	}

	public boolean updateUserInfo(AppUserDO appUserDO) {
		
		return userDAO.updateUserInfo(appUserDO);
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public AppUserDO getAppUser4Open(String openId,String openKey) {

		AppUserDO curUser = this.getAppUserByUserId(openId);
		if(curUser==null){
			AppUserDO appUserDO = new AppUserDO();
			appUserDO.setUserId(openId);
			appUserDO.setUserNick("");
			appUserDO.setLastLoginIp("a:1_0;b:1_0;c:1_0;d:1_0;e:1_0");
			this.userDAO.insertUser(appUserDO);
		}
		
		String userInterface = "/v3/user/get_info";

		AppUserDO userDO = new AppUserDO();
		userDO.setLastLoginIp(curUser.getLastLoginIp());
		userDO.setUserId(openId);
		 
		HashMap<String,String> params = new HashMap<String,String>();
		params.put("openid", openId);
		params.put("openkey", openKey);
		params.put("appid", String.valueOf(100678863));
		params.put("pf", "qzone");
		
		OpenApiV3 openApi = new OpenApiV3(String.valueOf(100678863),
				String.valueOf("3d7842f9c6b39977bf4e9526f881d1ba"));
		
		openApi.setServerName("119.147.19.43");
		
		
		try {
			String reqStr =  openApi.api(userInterface, params, "http");
			logger.error(reqStr);
			
			JSONObject jo = new JSONObject(reqStr);

	        userDO.setHeadPic((String)(jo.get("figureurl")));
	        userDO.setUserNick((String)(jo.get("nickname")));
	        logger.error(userDO.getUserNick());
	        logger.error(userDO.getHeadPic());
	        
	        
		} catch (Exception e) {
			logger.error(e.toString());
		}
		
		return userDO;
	}

}
